package com.keta.foundation.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.keta.foundation.dao.ModuleDAO;
import com.keta.foundation.entity.Module;
import com.keta.foundation.exception.ExistedException;
import com.keta.foundation.exception.NotDeletedException;
import com.keta.foundation.service.ModuleService;
import com.keta.foundation.util.dwz.Page;
import com.keta.foundation.util.dwz.PageUtil;

@Service
@Transactional
public class ModelServiceImpl implements ModuleService {

	private Logger log = LoggerFactory.getLogger(ModelServiceImpl.class);

	@Autowired
	private ModuleDAO moduleDAO;

	@Override
	public List<Module> getByParentId(Long parentId) {

		return moduleDAO.findByParentId(parentId);
	}

	@Override
	public List<Module> getByParentId(Long parentId, Page page) {
		org.springframework.data.domain.Page<Module> springPage = moduleDAO.findByParentId(parentId,
				PageUtil.createPageable(page));
		page.setTotalPage(springPage.getTotalPages());
		page.setTotalCount(springPage.getTotalElements());
		return springPage.getContent();
	}

	@Override
	public List<Module> getAll() {
		return moduleDAO.findAll();
	}

	@Override
	public List<Module> getAll(Page page) {
		org.springframework.data.domain.Page<Module> springPage = moduleDAO.findAll(PageUtil.createPageable(page));
		page.setTotalPage(springPage.getTotalPages());
		page.setTotalCount(springPage.getTotalElements());
		return springPage.getContent();
	}

	@Override
	public List<Module> getAll(Specification<Module> specification, Page page) {
		org.springframework.data.domain.Page<Module> springPage = moduleDAO.findAll(specification,
				PageUtil.createPageable(page));
		page.setTotalPage(springPage.getTotalPages());
		page.setTotalCount(springPage.getTotalElements());
		return springPage.getContent();
	}

	@Override
	public Module get(Long id) {
		return moduleDAO.findOne(id);
	}

	@Override
	public void saveOrUpdate(Module module) {
		if (module.getId() == null) {
			if (moduleDAO.getBySn(module.getSn()) != null) {
				throw new ExistedException("已存在sn=" + module.getSn() + "的模块。");
			}
		}

		moduleDAO.save(module);
	}

	@Override
	public void delete(Long id) {

		if (id == RootModuleId) {
			throw new NotDeletedException("跟节点不能删除");
		}

		moduleDAO.delete(id);
	}

}
